<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';

import { Form, FormItem, Input } from 'ant-design-vue';
import consola from 'consola';

import { DictEnum } from '#/enums/commonEnum';
import { useDictStore } from '#/store';

// 接收父组件传入的value
const props = defineProps<{
  type?: string;
  value?: string;
}>();

// 向父组件 emits 事件
const emit = defineEmits<{
  (e: 'update:value', value: string): void;
}>();

const i18nList = ref<any[]>([]);
const formData = reactive<Record<string, string | undefined>>({});
const formRef = ref<any>(null);

// 初始化表单数据和规则
const initForm = (jsonStr?: string) => {
  // 初始化表单规则
  i18nList.value.forEach((item) => {
    formData[item.key] = '';
  });

  if (jsonStr) {
    try {
      const parsed = JSON.parse(jsonStr);
      // 将解析后的数据赋值到表单
      Object.keys(parsed).forEach((key) => {
        formData[key] = parsed[key];
      });
    } catch (error) {
      console.error('解析JSON失败:', error);
    }
  }
};

// 处理输入变化
const handleInputChange = () => {
  emit('update:value', JSON.stringify(formData));
};

// 监听父组件传入的value变化
watch(
  () => props.value,
  (newVal) => {
    initForm(newVal);
  },
  { immediate: true },
);

// 监听语言列表变化，重新初始化表单
watch(
  () => i18nList.value,
  () => {
    initForm(props.value);
  },
);
const dictStore = useDictStore();

onMounted(async () => {
  try {
    // 获取语言列表
    const dictData = dictStore.getDictItemList(DictEnum.I18N_JSON);
    i18nList.value = dictData;
  } catch (error) {
    consola.error('获取语言字典失败:', error);
  }
});
</script>
<template>
  <Form
    ref="formRef"
    :model="formData"
    :label-col="{ span: 8 }"
    label-align="right"
  >
    <FormItem
      v-for="item in i18nList"
      :key="item.key"
      :label="item.name"
      :name="item.key"
    >
      <Input v-model:value="formData[item.key]" @input="handleInputChange" />
    </FormItem>
  </Form>
</template>
